package com.ymatou.shop.ui.activity.seller;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.ymatou.shop.R;
import com.ymatou.shop.api.ApiRequest;
import com.ymatou.shop.api.ApiResponse;
import com.ymatou.shop.cache.ImageCache;
import com.ymatou.shop.cache.RequestInfo;
import com.ymatou.shop.cache.exception.CacheException;
import com.ymatou.shop.model.Product;
import com.ymatou.shop.model.Seller;
import com.ymatou.shop.ui.activity.BaseHeaderListActivity;
import com.ymatou.shop.ui.adapter.BaseAdapter;
import com.ymatou.shop.ui.view.item.EventProductItemView;
import com.ymatou.shop.util.GlobalUtil;

public class EventListActivity extends BaseHeaderListActivity {
	
	public static final String EXTRA_SELLER_ID = "extra_seller_id";
	
	private static final int REQUEST_ID_USER_INFO = 0x01;
	private static final int REQUEST_ID_LIST = 0x02;
	private static final int REQUEST_ID_NEW_PRODUCT_NUM = 0x03;
	
	private BaseAdapter mAdapter;
	
	private List<Product> mProductList;
	private Seller mSeller;
	private int mSellerId;
	private String mLastProductId;
	private volatile boolean mReachEnd;
	private volatile boolean mLoadingList;
	private long mLastestCheckNewNumTime;
	
	private ImageView mHeaderImageView;
	private TextView mNewProductTextView;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_list);
		
		mSellerId = getIntent().getIntExtra(EXTRA_SELLER_ID, -1);
		if (mSellerId == -1) {
			finish();
			return;
		}
		
		mProductList = new ArrayList<Product>();
		mLastestCheckNewNumTime = System.currentTimeMillis();
		
		setupViews();
		
		setupSellerData();
	}
	
	@Override
	protected void setupViews() {
		super.setupViews();
		getTitleTextView().setText(R.string.title_event_list);
		getTitleLeftImageButton().setImageResource(R.drawable.back_icon);
		getTitleLeftImageButton().setVisibility(View.VISIBLE);
		getTitleLeftImageButton().setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		getTitleRightImageButton1().setImageResource(R.drawable.refresh_icon);
		getTitleRightImageButton1().setVisibility(View.VISIBLE);
		if (getAccount().isLogin()) {
			getTitleRightImageButton2().setImageResource(R.drawable.ren);
			getTitleRightImageButton2().setVisibility(View.VISIBLE);
			getTitleRightImageButton2().setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					GlobalUtil.startUserInfoActivity(v.getContext());					
				}
			});
		} else {
			getTitleRightButton().setText(R.string.btn_login);
			getTitleRightButton().setVisibility(View.VISIBLE);
			getTitleRightButton().setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					startLoginActivity();
				}
			});
		}
		
		changeLoadingViewState(false);
	}
	
	private void setupSeller() {
		View headerView = getLayoutInflater().inflate(R.layout.include_event_list_header, null);
		((TextView) headerView.findViewById(R.id.name_txt)).setText(mSeller.mName);
		((TextView) headerView.findViewById(R.id.address_txt)).setText(mSeller.mPosition);
		mHeaderImageView = (ImageView) headerView.findViewById(R.id.header_image);
		mNewProductTextView = (TextView) headerView.findViewById(R.id.new_product_txt);
		
		Drawable drawable = ImageCache.get(this, mSeller.mHeaderUrl, new ImageCache.OnIconLoadCompleteListener() {
			@Override
			public void onLoadComplete(String url, boolean success, Drawable drawable) {
				if (success) {
					mHeaderImageView.setImageDrawable(drawable);
				}
			}
		});
		if (drawable != null) {
			mHeaderImageView.setImageDrawable(drawable);
		}
		
		getListView().addHeaderView(headerView);
	}
	
	private void setupSellerData() {
		RequestInfo requestInfo = ApiRequest.getSellerInfo(mSellerId);
		getCacheManager().register(REQUEST_ID_USER_INFO, requestInfo, this);
	}
	
	private void setupNewProductNum() {
		RequestInfo requestInfo = ApiRequest.getSellerNewProductNum(mSellerId, mLastestCheckNewNumTime);
		getCacheManager().register(REQUEST_ID_NEW_PRODUCT_NUM, requestInfo, this);
	}
	
	@Override
	protected void setupData(boolean useCache) {
		if (!mReachEnd) {
			if (!mLoadingList) {
				mLoadingList = true;
				RequestInfo requestInfo = ApiRequest.getSellerEventProductList(mSeller.mActivityId, mLastProductId, 0, useCache);
				getCacheManager().register(REQUEST_ID_LIST, requestInfo, this);
			}
		}
	}
	
	@Override
	public BaseAdapter getAdapter() {
		return mAdapter;
	}
	
	@Override
	public void onCacheSuccess(int requestId, RequestInfo requestInfo,
			Object response) {
		if (requestId == REQUEST_ID_USER_INFO) {
			mSeller = ApiResponse.getSeller((String) response);
			if (mSeller == null) {
				changeErrorViewState(false);
				return;
			}
			setupSeller();
			
			setupData(true);
			setupNewProductNum();
		} else if (requestId == REQUEST_ID_LIST) {
			List<Product> list = ApiResponse.getProductList((String) response);
			if (list == null) {
				if (mProductList.size() == 0) {
					changeErrorViewState(false);
				}
				return;
			}
			
			if (mProductList.size() == 0) {
				mProductList.addAll(list);
				
				mAdapter = new EventListAdapter(this, mProductList, mSeller);
				getListView().setAdapter(mAdapter);
				
				changeLoadingViewState(true);
			} else {
				mProductList.addAll(list);
				mAdapter.notifyDataSetChanged();
			}
			
			if (list.isEmpty()) {
				mReachEnd = true;
			} else {
				mLastProductId = list.get(list.size() - 1).mId;
			}
			mLoadingList = false;
		} else if (requestId == REQUEST_ID_NEW_PRODUCT_NUM) {
			int num = ApiResponse.getSellerNewProductNum((String) response);
			if (num > 0) {
				mNewProductTextView.setText(getString(R.string.event_new_product, num));
				mNewProductTextView.setVisibility(View.VISIBLE);
			} else {
				mNewProductTextView.setVisibility(View.GONE);
			}
			mLastestCheckNewNumTime = System.currentTimeMillis();
		} else {
			super.onCacheSuccess(requestId, requestInfo, response);
		}
	}
	
	@Override
	public void onCacheFailed(int requestId, RequestInfo requestInfo,
			CacheException error) {
		if (requestId == REQUEST_ID_USER_INFO) {
			changeErrorViewState(false);
		} else if (requestId == REQUEST_ID_LIST) {
			changeErrorViewState(false);
		} else {
			super.onCacheFailed(requestId, requestInfo, error);
		}
	}
	
	private static class EventListAdapter extends BaseAdapter<Product> {
		
		private Seller mSeller;
		
		public EventListAdapter(Context context, List<Product> items, Seller seller) {
			super(context, items);
			mSeller = seller;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			EventProductItemView itemView;
			if (convertView == null) {
				itemView = new EventProductItemView(getContext(), mSeller , mOnIconLoadCompleteListener);
			} else {
				itemView = (EventProductItemView) convertView;
			}
			
			Product item = getItem(position);
			itemView.setData(item);
			
			return itemView;
		}
		
		private ImageCache.OnIconLoadCompleteListener mOnIconLoadCompleteListener = new ImageCache.OnIconLoadCompleteListener() {
			@Override
			public void onLoadComplete(String url, boolean success, Drawable drawable) {
				if (success) {
					notifyDataSetChanged();
				}
			}
		};
	}
}
